package com.ifacebox.web.admin.master.service;

import com.ifacebox.web.admin.master.dao.MasterNoticeDao;
import com.ifacebox.web.admin.master.dao.MasterUserNoticeDao;
import com.ifacebox.web.admin.master.model.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author znn
 */
@Service
public class MasterNoticeService {
    @Resource
    private MasterNoticeDao masterNoticeDao;
    @Resource
    private MasterUserNoticeDao masterUserNoticeDao;

    public List<MasterNotice> query(MasterNoticeQuery masterNoticeQuery) {
        List<MasterNotice> masterNoticeList = masterNoticeDao.query(masterNoticeQuery);
        for (MasterNotice masterNotice : masterNoticeList) {
            masterNotice.setStatusExplain(this.getStatusExplain(masterNotice.getStatusId()));
        }
        return masterNoticeList;
    }

    public Long total(MasterNoticeQuery masterNoticeQuery) {
        return masterNoticeDao.total(masterNoticeQuery);
    }

    public MasterNotice queryById(Integer id) {
        return masterNoticeDao.queryById(id);
    }

    public List<MasterUser> queryReadMasterUserByNoticeId(Integer noticeId) {
        return masterUserNoticeDao.queryReadMasterUserByNoticeId(noticeId);
    }

    public boolean save(MasterUser masterUser, MasterNotice masterNotice) {
        masterNotice.setCreateUser(masterUser.getUsername());
        return !ObjectUtils.isEmpty(masterNoticeDao.save(masterNotice));
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean edit(MasterUser masterUser, MasterNotice masterNotice) {
        masterNotice.setUpdateUser(masterUser.getUsername());
        if (!ObjectUtils.isEmpty(masterNoticeDao.edit(masterNotice))) {
            masterUserNoticeDao.deleteByNoticeId(masterNotice.getId());
            return true;
        }
        return false;
    }

    public void save(MasterUserNotice masterUserNotice) {
        if (ObjectUtils.isEmpty(masterUserNoticeDao.query(masterUserNotice))) {
            masterUserNoticeDao.save(masterUserNotice);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer id) {
        if (!ObjectUtils.isEmpty(masterNoticeDao.delete(id))) {
            masterUserNoticeDao.deleteByNoticeId(id);
            return true;
        }
        return false;
    }

    private String getStatusExplain(Integer statusId) {
        for (MasterNoticeStatus masterNoticeStatus : MasterNoticeStatus.values()) {
            if (masterNoticeStatus.getStatusId().equals(statusId)) {
                return masterNoticeStatus.getStatusExplain();
            }
        }
        return MasterMenuStatus.UNKNOWN.getStatusExplain();
    }
}
